package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func downloadFile(url, fliename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer r.Body.Close()

	f, err := os.Create(fliename)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	n, err := io.Copy(f, r.Body)
	fmt.Println(n, err)
}

type Reader struct {
	io.Reader
	Total   int64
	Current int64
}

func (r *Reader) Read(p []byte) (n int, err error) {
	n, err = r.Reader.Read(p)
	r.Current += int64(n)
	fmt.Printf("\r%.2f %%", (float64(r.Current*10000/r.Total) / 100))
	return
}

func DownloadFileProgress(url, fliename string) {
	r, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer r.Body.Close()

	f, err := os.Create(fliename)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	reader := &Reader{
		Reader: r.Body,
		Total:  r.ContentLength,
	}

	_, _ = io.Copy(f, reader)
	// fmt.Println(n, err)
}

func main() {
	// 自动文件下载
	urlStr := "https://i1.hdslb.com/bfs/face/0d2f52b9e1dae83b2cd710b38ee911533db32774.jpg"
	filename := "polo.png"
	// downloadFile(urlStr, filename)
	DownloadFileProgress(urlStr, filename)
}
